#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time    : 2021/3/3 16:16
# @Author  : zhaohexin
# @Email   : 1483643520@xxx.com
# @File    : main.py
# @Software: PyCharm
# @FileDescription：主路由

from typing import List
from fastapi import Depends, APIRouter, HTTPException, status
from sqlalchemy.orm import Session

from apps.system.users import crud, schemas
from common.Depts import get_db
from apps.system.api import crud as apiCrud
from apps.system.roles import crud as roleCrud
from apps.system.jobs import crud as jobCrud
from apps.system.depts import crud as deptCrud

router = APIRouter()


@router.post("/", response_model=schemas.User, summary="创建用户")
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    db_user = crud.get_user_by_email(db, email=user.email)
    if db_user:
        raise HTTPException(status_code=400, detail="该邮箱已被注册，请重新输入！")
    response = crud.create_user(db=db, user=user)
    return response


@router.get("", response_model=schemas.UsersWeb, summary="获取全部用户详情")
def read_users(page: int = 0, size: int = 10, sort: str = "id", db: Session = Depends(get_db),
               user_name: str = Depends(apiCrud.check_token)):
    """
    查看所有用户信息
    :param user_name: 登陆用户名
    :param page: 当前页
    :param size: 每页数量
    :param sort: 排序字段
    :param db:
    :return:
    """
    # 获取当前登陆用户所属权限
    user = crud.get_user_by_username(db, username=user_name)
    # 查询角色信息并进行赋值
    roles = roleCrud.get_roles_by_user(db, user_id=user.id)
    roles_permission = [role.data_scope for role in roles]
    roles_id = [role.id for role in roles]
    # 获取部门权限列表
    if "全部" in roles_permission:
        dept_permission = []
    elif "本级" in roles_permission:
        dept_permission = [user.dept_id]
    else:
        dept_permission = [permission.dept_id for permission in deptCrud.get_dept_by_role(db, roles_id)]

    users = [user.to_dict() for user in crud.get_users(db, dept_permission, page=page, size=size, sort=sort)]
    # 其他属性增加
    for user in users:
        user["dept"] = deptCrud.get_dept(db, dept_id=user.get("dept_id")).to_dict()
        user["roles"] = [role.to_dict() for role in roleCrud.get_roles_by_user(db, user_id=user.get("id"))]
        user["jobs"] = [job.to_dict() for job in jobCrud.get_jobs_by_user(db, user_id=user.get("id"))]
    users = {"content": users, "totalElements": len(users)}
    return users


@router.get("/{user_id}/", response_model=schemas.UserWeb, summary="获取指定用户详情")
def read_user(user_id: int, db: Session = Depends(get_db),
              check_token: str = Depends(apiCrud.check_token)):
    """
    获取单条用户信息
    :param check_token:
    :param user_id:
    :param db:
    :return:
    """
    db_user = crud.get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="用户未找到")
    return db_user.to_dict()
